package com.kwok.openplatform.controller;

import com.kwok.openplatform.common.constant.LoginConstant;
import com.kwok.openplatform.common.util.MD5Util;
import com.kwok.openplatform.entity.User;
import com.kwok.openplatform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public String register(User user){
        //获取前端输入的用户名
        String username = user.getUsername();
        //通过前端输入的用户名查询数据库是否存在该用户
        User registerUser = userService.queryUserByUsername(username);
        if (registerUser != null){
            //如果存在，则返回2
            return "2";
        } else {
            //进行用户注册之前，先采用MD5摘要算法将密码明文转为密文
            user.setPassword(MD5Util.encrypt(user.getPassword()));
            //调用service层的方法进行用户注册
            Integer register = userService.register(user);
            if (register > 0){
                return "1";
            } else {
                return "0";
            }
        }
    }

    @PostMapping("/login")
    public String login(User user,HttpSession session,String validCode){
        //生成的验证码
        String kaptcha = (String) session.getAttribute("kaptcha");
        //通过登录的用户名查询数据库是否存在该登录用户
        User loginUser = userService.queryUserByUsername(user.getUsername());
        if (loginUser == null){
//            System.out.println("用户不存在");
            return "0";
        } else if (!loginUser.getPassword().equals(MD5Util.encrypt(user.getPassword()))) {
//            System.out.println("密码错误");
            return "-1";
        } else if (!validCode.equals(kaptcha)) {
//            System.out.println("验证码错误");
            return "-2";
        }
        session.setAttribute("loginFlag", LoginConstant.LOGIN_SESSION_KEY);
//        session.setAttribute("username",loginUser.getUsername());
        return "1";
    }

    @PostMapping("/checkLogin")
    public String checkLogin(HttpSession session){
        //if (session.getAttribute("loginFlag") !=null && session.getAttribute("username") != null){
        if (session.getAttribute("loginFlag") !=null){
            return "1";
        }else {
            return "0";
        }
    }

    @PostMapping("/logout")
    public String logout(HttpSession session){
        //移除存在session中的登录凭证
        session.removeAttribute("loginFlag");
//        session.removeAttribute("username");
        return "1";
    }

}
